package TaskDb

import (
	"errors"
	"fmt"
	db "gitee.com/under-my-umbrella/gocode/db"
	"github.com/jmoiron/sqlx"
)

type Task struct {
	Id          int    `db:"id" json:"id"`
	UserId      int    `db:"user_id" json:"user_id"`
	Title       string `db:"title" json:"title"`
	Description string `db:"description" json:"description"`
	Due_Date    string `db:"due_date" json:"due_date"`
	Created_At  string `db:"created_at" json:"created_at"`
	Updated_At  string `db:"updated_at" json:"updated_at"`
}

var database *sqlx.DB

func init() {
	database = db.GetDB()
}

// GetAllTask 查询所有任务,通过UserId查询
func GetAllTask(UserId string) ([]Task, error) {
	var taskList []Task
	fmt.Println("UserId", UserId)
	if database == nil {
		return nil, errors.New("database connection is nil")
	}
	fmt.Println("执行到这里")
	query := "SELECT * FROM task where user_id = ?"
	err := database.Select(&taskList, query, UserId)
	fmt.Println("taskList", taskList)
	if err != nil {
		return nil, err
	}
	return taskList, nil
}

// GetTaskById 根据id查询任务
func GetTaskById(id string) (*Task, error) {
	var task Task
	if database == nil {
		return nil, errors.New("database connection is nil")
	}
	query := "SELECT * FROM task WHERE id = ?"
	err := database.Get(&task, query, id)
	if err != nil {
		return nil, err
	}
	return &task, nil
}

// SaveTask 保存任务
func SaveTask(task Task) {
	if database == nil {
		return
	}
	query := "INSERT INTO task (user_id, title, description, due_date, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"
	_, err := database.Exec(query, task.UserId, task.Title, task.Description, task.Due_Date, task.Created_At, task.Updated_At)
	if err != nil {
		fmt.Println(err)
	}
}

// UpdateTask 更新任务
func UpdateTask(id string, task Task) {
	if database == nil {
		return
	}
	query := "UPDATE task SET title = ?, description = ?, due_date = ?, updated_at = ? WHERE id = ?"
	_, err := database.Exec(query, task.Title, task.Description, task.Due_Date, task.Updated_At, id)
	if err != nil {
		fmt.Println(err)
	}
}

// DeleteTask 删除任务
func DeleteTask(id string) {
	if database == nil {
		return
	}
	query := "DELETE FROM task WHERE id = ?"
	_, err := database.Exec(query, id)
	if err != nil {
		fmt.Println(err)
	}
}
